package friendService

import (
	"chart.zozoo.net/app/dao/usersFriendsDao"
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"strconv"
	"time"
)

// List 获取好友列表
func List(uuid string, params ...string) (list []*usersFriendsDao.Friend, err error) {

	//获取用户信息
	userInfo, err := userService.InfoByUuid(uuid)
	if err != nil {
		return nil, err
	}

	//从数据库获取
	list = make([]*usersFriendsDao.Friend, 0)

	if len(params) == 0 {
		params = append(params, "get")
	}
	redisKey := "userFriends:uid:" + strconv.Itoa(userInfo.Id) + ":json"
	switch params[0] {
	case "update":
		break
	case "delete":
		myRedis.RedisClient.Del(redisKey)
		return nil, nil
	default:
		res := myRedis.RedisClient.Get(redisKey)
		if res.Err() == nil {
			val := res.Val()
			err = json.Unmarshal([]byte(val), &list)
			if err != nil {
				return nil, err
			}

			return list, nil
		}
	}

	list, err = usersFriendsDao.List(userInfo.Id)
	if err != nil {
		return nil, err
	}
	
	//保存缓存
	str, err := json.Marshal(list)
	if err != nil {
		return nil, err
	}
	myRedis.RedisClient.Set(redisKey, string(str), time.Hour*24)
	return list, nil
}
